package org.yi.fc.controller.admin.login;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import org.yi.fc.constants.FCConstants;
import org.yi.fc.controller.base.BaseController;
import org.yi.fc.entity.FUser;
import org.yi.fc.ext.render.FCCaptchaRender;
import org.yi.fc.utils.MathUtils;

import com.jfinal.plugin.activerecord.Db;

public class LoginController extends BaseController {

	//TODO 注册密码后端加密， 登陆密码前端加密后传入后端
	public void login() {
		
		if(METHOD_GTE.equalsIgnoreCase(getRequest().getMethod())){
			//FIXME index() --> forwardAction(actionUrl);
			index();
		} else if(METHOD_POST.equalsIgnoreCase(getRequest().getMethod())){
			List<FUser> users = new FUser().getUser(getPara("email"), getPara("password"));
			if(users == null || users.size() == 0) {			
				renderJson("isLogin",FCConstants.NOT_LOGIN);
			} else {
				//1已登录，0未登录
				if(users.size() == 0) {			
					renderJson("isLogin", "0" );
				} else {
					//1已登录，0未登录
					setSessionAttr("isLogin", "1")
					.setSessionAttr("f_user", users.get(0));
					
					Map<String,String> map = new HashMap<String, String>();
					map.put("isLogin", "1");
					map.put("go", "/admin/index");
					
					renderJson(map);
				}
			}
		} else {
			saveMessage("方法错误， 请求只接受get和post方法");
			forwardAction("/error");
		}
	}
	/**
	 * 进入首页
	 */
	public void index() {
		if( FCConstants.IS_LOGIN.equals( (String) getSessionAttr("isLogin") ) ){
			render("index.html");			
		}else{
			render("login.html");
		}
	}
	/**
	 * 鐢ㄦ埛娉ㄥ唽
	 */
	public void regist(){
		if(METHOD_GTE.equalsIgnoreCase(getRequest().getMethod())) {
			//进入注册页面
			render("regist.html");
		} else if(METHOD_POST.equalsIgnoreCase(getRequest().getMethod())) {
			FUser user = new FUser();
			String email = getPara("email");
			if(!isUserExist(email)) {
				//用户不存在， 则入库
				user.set("email", email)
				   .set("passwd", getPara("passwd"))
		  		   .set("salt", MathUtils.randomInt(1000, 9999))
		  		   .save();
				redirect("/admin/index");
			} else {
				saveMessage("%s 已存在！", email);
				render("regist.html");
			}
		} else {
			saveMessage("方法错误， 请求只接受get和post方法");
			forwardAction("/error");
		}
	}
	
	/**
	 * 判断用户是否存在， 存在返回true， 否则返回false
	 * @param email
	 * @return
	 */
	private boolean isUserExist(String email) {
		String sql = "select count(*) from f_user where email = ?";
		return Db.queryLong(sql, email) > 0;
	}
	
	/**
	 * ajax判断用户是否可注册
	 */
	public void exists() {
		Map<String,Object> obj = new HashMap<String,Object>();
		obj.put("exist", isUserExist(getPara("key")));
		renderJson(obj);
	}
	
	/**
	 *  用户退出登录
	 */
	public void logout(){
		destroyResources();
		getSession().invalidate();
		redirect("/admin/index");
	}
	
	/**
	 * 销毁用户占用的系统资源
	 */
	private void destroyResources(){
		
	}
	
	/**
	 * 生成随机验证码
	 */
	public void genCaptchaImg(){
		String codeKey = UUID.randomUUID().toString();
		FCCaptchaRender captchRender = new FCCaptchaRender(codeKey);
		render(captchRender);
	}
	
	/**
	 * 对验证码进行校验
	 */
	//FIXME valide --> validate
	public void valideCaptchaCode(){
		String capthcaCode = getPara(FCConstants.VERIFY_CODE);
		String codeInSession = getSessionAttr(FCConstants.VERIFY_CODE);
		renderJson("valide",codeInSession.equalsIgnoreCase(capthcaCode));
	}
}
